<?php
/**
 * Created by.
 * CaoMing
 * 2019-09-22
 * 20:50
 */

namespace App\Http\Controllers;


use App\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    //文章列表页
    public function index()
    {
        $posts = Post::orderBy('created_at','desc')->paginate(6);
        return view('post/index',compact('posts'));
    }
    //文章详情页
    public function show(Post $post)
    {

        return view('post/show',compact('post'));
    }
    //创建文章页
    public function create()
    {

        return view('post/create');
    }
    //文章编辑页
    public function edit(Post $post)
    {

        return view('post/edit',compact('post'));
    }
    //创建文章逻辑
    public function store()
    {

        $re = Post::create(request(['title','content']));
        if ($re){
            return redirect('/posts');
        }
        else {
            echo 'fail';
        }
    }
    //编辑文章逻辑
    public function update(Post $post)
    {
         //验证
        $this->validate(request(),[
            'title'=>'required|string|max:100|min:5',
            'content'=>'required|string|min:10'
        ]);
        //逻辑
        $post->title = request('title');
        $post->content = request('content');
        $re= $post->save();
        if ($re){
            //渲染
            return redirect('/posts/'.$post->id);
        }
        else {
            echo 'fail';
        }


    }
    //上传图片
    public function imageUpload(Request $request)
    {
        $path = $request->file('wangEditorH5File')->storePublicly(md5(time()));
        return asset('storage/'.$path);
    }
    //删除文章逻辑
    public function delete(Post $post)
    {
        //TODO:用户权限认证
        $post->delete();
        return redirect('/posts');
    }
}